package com.yipei.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.yipei.business.domain.MlPositionShare;
import com.yipei.business.domain.MlTradeEntrustOrder;
import com.yipei.business.domain.MlTradingGroup;
import com.yipei.business.service.*;
import com.yipei.business.service.impl.MlTradeEntrustOrderServiceImpl;
import com.yipei.business.vo.*;
import com.yipei.common.annotation.Log;
import com.yipei.common.core.controller.BaseController;
import com.yipei.common.core.domain.AjaxResult;
import com.yipei.common.core.domain.entity.MlTradeAccount;
import com.yipei.common.core.page.TableDataInfo;
import com.yipei.common.enums.BusinessType;
import com.yipei.common.utils.poi.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 交易群主Controller
 *
 * @author yipei
 * @date 2025-06-25
 */
@RestController
@RequestMapping("/business/group")
public class MlTradingGroupController extends BaseController {
    @Autowired
    private IMlTradingGroupService mlTradingGroupService;
    @Autowired
    private IMlTradeAccountService iMlTradeAccountService;

    @Autowired
    private IMlPositionShareService mlPositionShareService;

    @Autowired
    private IMlTradeEntrustOrderService mlTradeEntrustOrderService;
    @Autowired
    private IMlKLineMasterService iMlKLineMasterService;

    /**
     * 查询交易群主列表
     */
    @PreAuthorize("@ss.hasPermi('business:group:list')")
    @GetMapping("/list")
    public TableDataInfo list(MlTradingGroup mlTradingGroup) {
        startPage();
        List<MlTradingGroup> list = mlTradingGroupService.selectMlTradingGroupList(mlTradingGroup);
        return getDataTable(list);
    }

    /**
     * 导出交易群主列表
     */
    @PreAuthorize("@ss.hasPermi('business:group:export')")
    @Log(title = "交易群主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MlTradingGroup mlTradingGroup) {
        List<MlTradingGroup> list = mlTradingGroupService.selectMlTradingGroupList(mlTradingGroup);
        ExcelUtil<MlTradingGroup> util = new ExcelUtil<MlTradingGroup>(MlTradingGroup.class);
        util.exportExcel(response, list, "交易群主数据");
    }

    /**
     * 获取交易群主详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:group:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(mlTradingGroupService.selectMlTradingGroupById(id));
    }

    /**
     * 新增交易群主
     */
    @PreAuthorize("@ss.hasPermi('business:group:add')")
    @Log(title = "交易群主", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MlTradingGroup mlTradingGroup) {
        return toAjax(mlTradingGroupService.insertMlTradingGroup(mlTradingGroup));
    }

    /**
     * 修改交易群主
     */
    @PreAuthorize("@ss.hasPermi('business:group:edit')")
    @Log(title = "交易群主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MlTradingGroup mlTradingGroup) {
        return toAjax(mlTradingGroupService.updateMlTradingGroup(mlTradingGroup));
    }

    /**
     * 删除交易群主
     */
    @PreAuthorize("@ss.hasPermi('business:group:remove')")
    @Log(title = "交易群主", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(mlTradingGroupService.deleteMlTradingGroupByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('business:group:list')")
    @GetMapping("/listGroup")
    public AjaxResult listGroup(MlTradingGroup mlTradingGroup) {
        startPage();
        List<MlTradingGroup> list = mlTradingGroupService.lambdaQuery().isNull(MlTradingGroup::getMainId).list();
        return AjaxResult.success(list);
    }

    /**
     * 添加群组成员
     *
     * @param mlTradingGroup
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:group:list')")
    @PostMapping("/addGroupUser")
    public AjaxResult addGroupUser(@RequestBody MlTradingGroup mlTradingGroup) {
        int list = mlTradingGroupService.addGroupUser(mlTradingGroup);
        return AjaxResult.success("添加成功");
    }

    /**
     * 查找群组成员
     *
     * @param mlTradingGroup
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:group:list')")
    @GetMapping("/listGroupUser")
    public AjaxResult listGroupUser(MlTradingGroup mlTradingGroup) {
        startPage();
        List<MlTradingGroup> list = mlTradingGroupService.lambdaQuery().eq(MlTradingGroup::getMainId, mlTradingGroup.getId()).list();
        return AjaxResult.success(list);
    }


    @ApiOperation("持仓股票获取数据")
    @GetMapping("/optlist")
    public AjaxResult optlist(@RequestParam String tdAccs) throws IOException {
        List<String> tdAccList = Arrays.asList(tdAccs.split(","));
        List<PositionShareVo> positionShareVoList = new ArrayList<>();
        for (String s : tdAccList) {
            LambdaQueryWrapper<MlTradeAccount> mlTradeAccountLambdaQueryWrapper = new LambdaQueryWrapper<>();
            mlTradeAccountLambdaQueryWrapper.eq(MlTradeAccount::getTdAcc, s);
            MlTradeAccount one = iMlTradeAccountService.getOne(mlTradeAccountLambdaQueryWrapper);
            LambdaQueryWrapper<MlPositionShare> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(MlPositionShare::getTdAcc, one.getTdAcc());
            List<MlPositionShare> mlPositionShares = mlPositionShareService.list(lambdaQueryWrapper);
            mlTradingGroupService.createpositionShareData(positionShareVoList, mlPositionShares, one);
        }
        return AjaxResult.success(positionShareVoList);
    }

    /**
     * 批量买入/卖出
     */

    @PostMapping("/batchBuyData")
    @Transactional
    public AjaxResult buySymbols(@RequestBody GroupVo groupVo) throws Exception {
        List<MlTradingGroup> users = groupVo.getUsers();
        List<SymbolsVo> symbols = groupVo.getSymbols();
        for (MlTradingGroup user : users) {
            for (SymbolsVo symbol : symbols) {
                /**
                 * 构造数据
                 */
                EntrustOrderVo entrustOrderVo = new EntrustOrderVo();
                MlTradeEntrustOrder mlTradeEntrustOrder = new MlTradeEntrustOrder();
                MlKLineMasterVo mlKLineMasterVo = new MlKLineMasterVo();
                String name = symbol.getName();
                if (name != null && name.contains(" ")) {
                    String[] arr = name.trim().split("\\s+");
                    if (arr.length >= 1) {
                        mlTradeEntrustOrder.setSecName(arr[0]);
                        mlTradeEntrustOrder.setSymbol(arr[1]);
                        mlKLineMasterVo.setF14(arr[0]);
                        mlKLineMasterVo.setF12(arr[1]);
                    }
                }
                mlTradeEntrustOrder.setTdAcc(user.getTdAcc());
                String wt = mlTradeEntrustOrderService.createrDH("WT");
                mlTradeEntrustOrder.setWtDh(wt);
                mlTradeEntrustOrder.setWtFx(new BigDecimal(groupVo.getDirection()));
                mlTradeEntrustOrder.setWtSl(new BigDecimal(symbol.getCount()));
                List<TodayDaealVo> todayDaeas = mlTradeEntrustOrderService.getTodayDaea(mlTradeEntrustOrder.getSymbol(), mlTradeEntrustOrder.getSecName());
                if (mlTradeEntrustOrder.getWtFx().equals(BigDecimal.ZERO)) {
                    List<TodayDaealVo> resultList = mlTradeEntrustOrderService.buildToday(todayDaeas);
                    for (TodayDaealVo todayDaealVo : resultList) {
                        if (new BigDecimal(symbol.getPrice()).compareTo(todayDaealVo.getPrice()) >= 0) {
                            mlTradeEntrustOrderService.getBigDecimal(mlTradeEntrustOrder, todayDaealVo);
                            createOrderGroup(user, symbol, entrustOrderVo, mlTradeEntrustOrder, mlKLineMasterVo);
                            return AjaxResult.success("买入成功");
                        } else {
                            /**
                             *
                             * 执行创建委托单，加进定时任务，扫描委托单，走成交逻辑
                             *
                             */
                            MlTradeAccount mlTradeAccount = iMlTradeAccountService.lambdaQuery().eq(MlTradeAccount::getTdAcc, mlTradeEntrustOrder.getTdAcc()).one();
                            BigDecimal cash = mlTradeAccount.getCash();
                            mlTradeEntrustOrder.setWtJg(new BigDecimal(symbol.getPrice()));
                            if (mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(cash) > 0 && mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(mlTradeAccount.getDjCash()) > 0 && mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(mlTradeAccount.getKqZj()) > 0) {
                                return AjaxResult.error("资金不足");
                            }
                            mlTradeEntrustOrderService.createmlTradeEntrustOrder(mlTradeEntrustOrder);
                            mlTradeEntrustOrderService.createmlTradeEntrustAddOrsubtract(mlTradeAccount, mlTradeEntrustOrder);
                            return AjaxResult.success("创建买入委托单成功");
                        }
                    }
                } else {
                    List<TodayDaealVo> resultList = mlTradeEntrustOrderService.createStoday(todayDaeas);
                    for (TodayDaealVo todayDaealVo : resultList) {
                        if (new BigDecimal(symbol.getPrice()).compareTo(todayDaealVo.getPrice()) <= 0) {
                            mlTradeEntrustOrderService.getBigDecimal(mlTradeEntrustOrder, todayDaealVo);
                            createOrderGroup(user, symbol, entrustOrderVo, mlTradeEntrustOrder, mlKLineMasterVo);
                            return AjaxResult.success("卖出成功");
                        } else {
                            LocalDate date = LocalDateTime.now().toLocalDate();
                            LambdaQueryWrapper<MlPositionShare> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                            lambdaQueryWrapper.eq(MlPositionShare::getTdAcc, user.getTdAcc()).eq(MlPositionShare::getSymbol, mlTradeEntrustOrder.getSymbol()).lt(MlPositionShare::getCreateTime,date).orderByAsc(MlPositionShare::getCreateTime);
                            List<MlPositionShare> mlPositionShares = mlPositionShareService.list(lambdaQueryWrapper);
                            BigDecimal kycwTotal = mlPositionShares.stream().map(MlPositionShare::getKyCw).reduce(BigDecimal.ZERO, BigDecimal::add);
                            if (mlTradeEntrustOrder.getWtSl().compareTo(kycwTotal) > 0) {
                                return AjaxResult.error("可用仓位不足");
                            }
                            mlTradeEntrustOrder.setWtJg(new BigDecimal(symbol.getPrice()));
                            mlTradeEntrustOrderService.mlPositionShareSdCw(mlTradeEntrustOrder,mlPositionShares);
                            mlTradeEntrustOrderService.createmlTradeEntrustOrder(mlTradeEntrustOrder);
                            mlTradeEntrustOrder.setCjSl(BigDecimal.ZERO);
                            return AjaxResult.success("创建卖出委托单成功");
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    private void createOrderGroup(MlTradingGroup user, SymbolsVo symbol, EntrustOrderVo entrustOrderVo, MlTradeEntrustOrder mlTradeEntrustOrder, MlKLineMasterVo mlKLineMasterVo) throws Exception {
        mlKLineMasterVo.setUpper_limit(symbol.getUpLimit());
        mlKLineMasterVo.setLower_limit(symbol.getDownLimit());
        entrustOrderVo.setMlTradeEntrustOrder(mlTradeEntrustOrder);
        entrustOrderVo.setMlKLineMasterVo(mlKLineMasterVo);
        mlTradingGroupService.addEntrustOrderGroup(entrustOrderVo);
    }

    /**
     * Batch opening
     * 批量开仓
     */
    @PostMapping("/batchOpening")
    @Transactional
    public AjaxResult batchOpening(@RequestBody GroupVo groupVo) throws Exception {
        List<MlTradingGroup> users = groupVo.getUsers();
        List<SymbolsVo> symbols = groupVo.getSymbols();
        for (MlTradingGroup user : users) {
            for (SymbolsVo symbol : symbols) {
                /**
                 * 构造数据
                 */
                EntrustOrderVo entrustOrderVo = new EntrustOrderVo();
                MlTradeEntrustOrder mlTradeEntrustOrder = new MlTradeEntrustOrder();
                MlKLineMasterVo mlKLineMasterVo = new MlKLineMasterVo();
                String name = symbol.getName();
                if (name != null && name.contains(" ")) {
                    String[] arr = name.trim().split("\\s+");
                    if (arr.length >= 1) {
                        mlTradeEntrustOrder.setSecName(arr[0]);
                        mlTradeEntrustOrder.setSymbol(arr[1]);
                        mlKLineMasterVo.setF14(arr[0]);
                        mlKLineMasterVo.setF12(arr[1]);
                    }
                }
                MlTradeAccount mlTradeAccount = iMlTradeAccountService.lambdaQuery().eq(MlTradeAccount::getTdAcc, user.getTdAcc()).one();
                BigDecimal cash = mlTradeAccount.getCash();
                //股票具体资金
                BigDecimal multiplyCash = cash.multiply(new BigDecimal(symbol.getOpenRatio())).divide(new BigDecimal(100));
                BigDecimal symbolCash = multiplyCash.multiply(new BigDecimal(symbol.getRatio())).divide(new BigDecimal(100));
                mlKLineMasterVo.setUpper_limit(symbol.getUpLimit());
                mlKLineMasterVo.setLower_limit(symbol.getDownLimit());
                List<TodayDaealVo> todayDaeas = mlTradeEntrustOrderService.getTodayDaea(mlTradeEntrustOrder.getSymbol(), mlTradeEntrustOrder.getSecName());
                mlTradeEntrustOrder.setWtFx(new BigDecimal(groupVo.getDirection()));
                if (mlTradeEntrustOrder.getWtFx().equals(BigDecimal.ZERO)) {
                    List<TodayDaealVo> resultList = mlTradeEntrustOrderService.buildToday(todayDaeas);
                    for (TodayDaealVo todayDaealVo : resultList) {
                        if (new BigDecimal(symbol.getOpenPrice()).compareTo(todayDaealVo.getPrice()) >= 0) {
                            mlTradeEntrustOrder.setWtJg(todayDaealVo.getPrice());
                            BigDecimal wtsl = symbolCash.divide(mlTradeEntrustOrder.getWtJg(), 0, BigDecimal.ROUND_DOWN);
                            mlTradeEntrustOrder.setWtSl(wtsl);
                            mlTradeEntrustOrderService.getBigDecimal(mlTradeEntrustOrder, todayDaealVo);
                            mlTradeEntrustOrder.setTdAcc(user.getTdAcc());
                            entrustOrderVo.setMlKLineMasterVo(mlKLineMasterVo);
                            if (mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(cash) > 0 && mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(mlTradeAccount.getDjCash()) > 0 && mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(mlTradeAccount.getKqZj()) > 0) {
                                return AjaxResult.error("资金不足");
                            }
                            entrustOrderVo.setMlTradeEntrustOrder(mlTradeEntrustOrder);
                            mlTradingGroupService.addEntrustOrderGroup(entrustOrderVo);
                            return AjaxResult.success("买入成功");
                        } else {
                            /**
                             *
                             * 执行创建委托单，加进定时任务，扫描委托单，走成交逻辑
                             *
                             */
                            mlTradeEntrustOrder.setWtJg(new BigDecimal(symbol.getOpenPrice()));
                            BigDecimal wtsl = symbolCash.divide(mlTradeEntrustOrder.getWtJg(), 0, BigDecimal.ROUND_DOWN);
                            mlTradeEntrustOrder.setWtSl(wtsl);
                            mlTradeEntrustOrder.setTdAcc(user.getTdAcc());
                            mlTradeEntrustOrder.setWtJg(new BigDecimal(symbol.getPrice()));
                            if (mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(cash) > 0 && mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(mlTradeAccount.getDjCash()) > 0 && mlTradeEntrustOrder.getWtJg().multiply(mlTradeEntrustOrder.getWtSl()).compareTo(mlTradeAccount.getKqZj()) > 0) {
                                return AjaxResult.error("资金不足");
                            }
                            mlTradeEntrustOrderService.createmlTradeEntrustOrder(mlTradeEntrustOrder);
                            mlTradeEntrustOrderService.createmlTradeEntrustAddOrsubtract(mlTradeAccount, mlTradeEntrustOrder);
                            return AjaxResult.success("创建买入委托单成功");
                        }

                    }
                }
            }
        }
        return null;
    }

    /**
     * Batch opening
     * 批量卖出
     */
    @PostMapping("/batchSellSymbol")
    @Transactional
    public AjaxResult batchSellSymbol(@RequestBody GroupVo groupVo) throws Exception {
        List<MlTradingGroup> users = groupVo.getUsers();
        List<SymbolsVo> symbols = groupVo.getSymbols();
        if (groupVo.getBatchCloseMode().equals("百分比") || groupVo.getBatchCloseMode().equals("列表")) {
            for (MlTradingGroup user : users) {
                for (SymbolsVo symbol : symbols) {
                    /**
                     * 构造数据
                     */
                    EntrustOrderVo entrustOrderVo = new EntrustOrderVo();
                    MlTradeEntrustOrder mlTradeEntrustOrder = new MlTradeEntrustOrder();
                    MlKLineMasterVo mlKLineMasterVo = new MlKLineMasterVo();
                    String name = symbol.getName();
                    if (name != null && name.contains(" ")) {
                        String[] arr = name.trim().split("\\s+");
                        if (arr.length >= 1) {
                            mlTradeEntrustOrder.setSecName(arr[0]);
                            mlTradeEntrustOrder.setSymbol(arr[1]);
                            mlKLineMasterVo.setF14(arr[0]);
                            mlKLineMasterVo.setF12(arr[1]);
                        }
                    }
                    LambdaQueryWrapper<MlPositionShare> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(MlPositionShare::getTdAcc, user.getTdAcc()).eq(MlPositionShare::getSymbol, mlTradeEntrustOrder.getSymbol());
                    MlPositionShare mlPositionShare = mlPositionShareService.getOne(lambdaQueryWrapper);
                    if (ObjectUtils.isEmpty(mlPositionShare)) {
                        throw new Exception("账号[" + user.getTdAcc() + "]没有[" + mlTradeEntrustOrder.getSecName() + "]持仓股票,请重新选择!");
                    }
                    BigDecimal kyCw = mlPositionShare.getKyCw();
                    mlKLineMasterVo.setUpper_limit(symbol.getUpLimit());
                    mlKLineMasterVo.setLower_limit(symbol.getDownLimit());
                    mlKLineMasterVo.setSellPanKouVos(symbol.getSellPanKouVos());
                    mlKLineMasterVo.setBuyPanKouVos(symbol.getBuyPanKouVos());
                    entrustOrderVo.setMlTradeEntrustOrder(mlTradeEntrustOrder);
                    entrustOrderVo.setMlKLineMasterVo(mlKLineMasterVo);
                    List<TodayDaealVo> todayDaeas = mlTradeEntrustOrderService.getTodayDaea(mlTradeEntrustOrder.getSymbol(), mlTradeEntrustOrder.getSecName());
                    List<TodayDaealVo> resultList = mlTradeEntrustOrderService.createStoday(todayDaeas);
                    for (TodayDaealVo todayDaealVo : resultList) {
                        if (new BigDecimal(symbol.getClosePrice()).compareTo(todayDaealVo.getPrice()) <= 0) {
                            mlTradeEntrustOrder.setWtFx(new BigDecimal(groupVo.getDirection()));
                            mlTradeEntrustOrder.setWtSl(kyCw.multiply(new BigDecimal(symbol.getCloseRatio())).divide(new BigDecimal(100), 0, BigDecimal.ROUND_DOWN));
                            mlTradeEntrustOrderService.getBigDecimal(mlTradeEntrustOrder, todayDaealVo);
                            mlTradeEntrustOrder.setTdAcc(user.getTdAcc());
                            mlTradingGroupService.addEntrustOrderGroup(entrustOrderVo);
                            return AjaxResult.success("卖出成功");
                        } else {
                            mlTradeEntrustOrder.setWtFx(new BigDecimal(groupVo.getDirection()));
                            mlTradeEntrustOrder.setWtJg(new BigDecimal(symbol.getClosePrice()));
                            mlTradeEntrustOrder.setWtSl(kyCw.multiply(new BigDecimal(symbol.getCloseRatio())).divide(new BigDecimal(100), 0, BigDecimal.ROUND_DOWN));
                            mlTradeEntrustOrder.setTdAcc(user.getTdAcc());
                            mlTradeEntrustOrderService.createmlTradeEntrustOrder(mlTradeEntrustOrder);
                            return AjaxResult.success("创建卖出委托单成功");
                        }
                    }

                }
            }
        } else {
            for (MlTradingGroup user : users) {
                String tdAcc = user.getTdAcc();
                LambdaQueryWrapper<MlPositionShare> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(MlPositionShare::getTdAcc, tdAcc).ne(MlPositionShare::getKyCw, "0");
                List<MlPositionShare> mlPositionShares = mlPositionShareService.list(lambdaQueryWrapper);
                String secName = "";
                for (MlPositionShare mlPositionShare : mlPositionShares) {
                    String symbol = "sh" + mlPositionShare.getSymbol() + ",sz" + mlPositionShare.getSymbol() + ",bj" + mlPositionShare.getSymbol();
                    HttpClient client = HttpClients.createDefault();
                    HttpGet request = new HttpGet("https://sqt.gtimg.cn/?q=" + symbol + "&fmt=json&app=wstock&t=" + System.currentTimeMillis());
                    request.setHeader("Content-Type", "text/javascript;charset=UTF-8");
                    HttpResponse response = client.execute(request);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();
                        String json = EntityUtils.toString(entity, "UTF-8").replace("jQuery", "");
                        Gson gson = new Gson();
                        JsonObject obj = gson.fromJson(json, JsonObject.class);
                        for (String code : obj.keySet()) {
                            JsonArray arr = obj.getAsJsonArray(code);
                            secName = arr.get(1).getAsString();
                        }
                    }
                    List<MlKLineMasterVo> symbolInfo = iMlKLineMasterService.getSymbolInfo(mlPositionShare.getSymbol(), secName);
                    EntrustOrderVo entrustOrderVo = new EntrustOrderVo();
                    MlTradeEntrustOrder mlTradeEntrustOrder = new MlTradeEntrustOrder();
                    MlKLineMasterVo mlKLineMasterVo = new MlKLineMasterVo();
                    mlTradeEntrustOrder.setSecName(mlPositionShare.getSec_name());
                    mlTradeEntrustOrder.setSymbol(mlPositionShare.getSymbol());
                    mlKLineMasterVo.setSellPanKouVos(symbolInfo.get(0).getSellPanKouVos());
                    mlKLineMasterVo.setBuyPanKouVos(symbolInfo.get(0).getBuyPanKouVos());
                    mlTradeEntrustOrder.setWtFx(new BigDecimal(groupVo.getDirection()));
                    List<TodayDaealVo> todayDaeas = mlTradeEntrustOrderService.getTodayDaea(mlTradeEntrustOrder.getSymbol(), mlTradeEntrustOrder.getSecName());
                    List<TodayDaealVo> resultList = mlTradeEntrustOrderService.createStoday(todayDaeas);
                    for (TodayDaealVo todayDaealVo : resultList) {
                            if (new BigDecimal(symbolInfo.get(0).getF2()).compareTo(todayDaealVo.getPrice()) <= 0) {
                                mlTradeEntrustOrder.setWtJg(todayDaealVo.getPrice());
                                mlTradeEntrustOrder.setWtSl(mlPositionShare.getKyCw());
                                mlTradeEntrustOrder.setTdAcc(user.getTdAcc());
                                mlKLineMasterVo.setUpper_limit(symbolInfo.get(0).getUpper_limit());
                                mlKLineMasterVo.setLower_limit(symbolInfo.get(0).getLower_limit());
                                mlKLineMasterVo.setF14(secName);
                                mlKLineMasterVo.setF12(mlPositionShare.getSymbol());
                                entrustOrderVo.setMlTradeEntrustOrder(mlTradeEntrustOrder);
                                entrustOrderVo.setMlKLineMasterVo(mlKLineMasterVo);
                                entrustOrderVo.setMlTradeEntrustOrder(mlTradeEntrustOrder);
                                entrustOrderVo.setMlKLineMasterVo(mlKLineMasterVo);
                                mlTradingGroupService.addEntrustOrderGroup(entrustOrderVo);
                                return AjaxResult.success("卖出成功");
                            } else {
                                mlTradeEntrustOrder.setWtJg(new BigDecimal(symbolInfo.get(0).getF2()));
                                mlTradeEntrustOrder.setWtSl(mlPositionShare.getKyCw());
                                mlTradeEntrustOrder.setTdAcc(user.getTdAcc());
                                mlTradeEntrustOrderService.createmlTradeEntrustOrder(mlTradeEntrustOrder);
                                return AjaxResult.success("创建卖出委托单成功");
                            }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 批量撤单
     */

    @PostMapping("/entrustOrderCancel")
    public AjaxResult entrustOrderCancel(@RequestBody GroupVo groupVo) throws Exception {
        List<MlTradingGroup> users = groupVo.getUsers();
        for (MlTradingGroup user : users) {
            List<MlTradeEntrustOrder> list = mlTradeEntrustOrderService.lambdaQuery().eq(MlTradeEntrustOrder::getTdAcc, user.getTdAcc()).notIn(MlTradeEntrustOrder::getWtZt, "0", "1", "2").list();
            for (MlTradeEntrustOrder mlTradeEntrustOrder : list) {
                mlTradeEntrustOrderService.entrustOrderCancel(String.valueOf(mlTradeEntrustOrder.getId()));
            }
        }
        return AjaxResult.success("批量撤单成功");
    }

    @ApiOperation("持仓股票获取数据")
    @GetMapping("/searchAccount")
    public AjaxResult searchAccount() throws IOException {
        List<MlTradeAccount> list = iMlTradeAccountService.lambdaQuery().select(MlTradeAccount::getTdAcc).list(); // 自定义方法
        // 转成 { label, value } 格式供前端用

        return AjaxResult.success(list);
    }


}
